import axios from 'axios'
import {getItem} from "@/utils/SystemUtil";

const timeout: number = 15000;

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
export function formatError(status: number) {
    if (status == 401) {
        return Promise.resolve({
            code: status,
            message: '登陆过期,重新登录!'
        })
    } else if (status == 404) {
        return {
            code: status,
            message: '访问资源不存在!'
        };
    } else if (status == 500) {
        return {
            code: status,
            message: '服务器内部错误!'
        }
    } else if (status == 503) {
        return {
            code: status,
            message: '服务器不可用!'
        }
    } else if (status != 200) {
        return Promise.resolve({
            code: status,
            message: '服务器忙，请稍后再试!'
        })
    }
}

export function createAxios(baseUrl: string) {
    const service = axios.create({
        // axios请求基础URL
        // 由于本项目使用mock + vite-plugin-mock启动的mock服务，默认使用的端口号与页面一致
        baseURL: baseUrl,
        timeout: timeout
    });

    // 设置请求拦截器
    service.interceptors.request.use(
        (config) => {
            // 添加请求头参数
            config.headers['UNI_MASTER_SESSION_ID'] = getItem('UNI_MASTER_SESSION_ID');

            return config;
        },
        (error) => {
            return Promise.reject(error)
        }
    )
    // 设置响应拦截器
    service.interceptors.response.use(
        (res) => {
            return res;
        },
        (error) => {
            error.response.data = formatError(error.response.status);
            return Promise.resolve(error.response);
        }
    )

    return service;
}

// axios对象
const service = createAxios(import.meta.env.VITE_APP_BASE_API);

export default service;
